package nl.hva.three2learn.dao;

import java.util.List;

import nl.hva.three2learn.model.Answer;
import nl.hva.three2learn.model.Question;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public final class QuestionDaoImpl implements QuestionDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Question findById(long questionId) {

		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();

		Query q = session.createQuery("from Question q where q.id = :id");
		q.setLong("id", questionId);

		Object result = q.uniqueResult();

		session.getTransaction().commit();

		if (result == null)
			return null;

		return (Question) result;
	}

	@Override
	public void save(Question question) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(question);
		session.getTransaction().commit();
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public List<Question> findAllQuestions() {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();

		Query q = session.createQuery("from Question");

		List<Question> questions = q.list();

		session.getTransaction().commit();

		return questions;
	}

	@Override
	public void remove(Question question) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		for(Answer a: question.getAnswers()) {
			a.setQuestion(null);
			session.delete(a);
		}
		
		question.setAnswers(null);
		
		session.delete(question);
		
		session.getTransaction().commit();
	}
}
